//
//  LSZFindOutMoreVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018年1月9日 星期二.
//  Copyright © 2017年 LC. All rights reserved.
//
//if ([self.type isEqualToString:@"2"]) {
//        http://buy.9ku.com/apifuyin/shoplogin?userid=1317&time=1511420900807&sign=7efb6e370964ce6ffda3ae588fa04846&backurl=http://buy.9ku.com/wap/goods/goodsdetail?id=33
//

#import "LSZFindOutMoreVC.h"
#import "LSZFindOutMoreVC+LCMenu.h"
#import "zhAlertView.h"

extern CFAbsoluteTime StartTime;
@interface LSZFindOutMoreVC ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@end

@implementation LSZFindOutMoreVC
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.webView clearHTMLCache];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"LCPAWebViewLoadFail" object:nil];
}
- (void)dealloc {
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
    self.progressView.hidden = YES;
    [self.progressView removeFromSuperview];
    [self.view removeAllSubviews];
    self.webView.UIDelegate = nil;
    self.webView.navigationDelegate = nil;
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNVAndMenu];//创建菜单
    if ([self.type isEqualToString:@"2"]) {
        NSString *url = [NSString stringWithFormat:@"%@?%@&backurl=%@",@"http://buy.9ku.com/apifuyin/shoplogin",[UserPageManager getUrlStrMove],self.link];
        self.link = url;
    }else{
        self.link = [NSString stringWithFormat:@"%@?%@",shoopLogin,[UserPageManager getUrlStrMove]];
        self.view.hidden = YES;
        [PAWebView shareInstance].link = self.link;
        [[PAWebView shareInstance].webView.scrollView setContentOffset:CGPointMake(0,0) animated:NO];
        [[PAWebView shareInstance] callJS:@"document.title" handler:^(id response, NSError *error) {
            NSLog(@"response = %@", response);
            if (![response containsString:@"九酷福音"]/*这里判断是否打开网站成功*/) {
                [self.webView clearHTMLCache];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.view.hidden = NO;
                    [PAWebView shareInstance].view.hidden = YES;
                });
            }
        }];
        //添加页面跳转通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadFailFromNotification:) name:@"LCPAWebViewLoadFail" object:nil];
        [PAWebView shareInstance].view.hidden = NO;
        CGFloat sTime = (CFAbsoluteTimeGetCurrent()-StartTime);
//        NSLog(@"App启动时间--%f",sTime);
        if (sTime > 60*20) {//确保启动完APP20分登录失效再次
            self.view.hidden = NO;
            [PAWebView shareInstance].view.hidden = YES;
        }
    }
    if (self.titleStr) {
        self.title = self.titleStr;
    }else{
        self.title = @"主内商城";
    }
//    NSLog(@"调转链接 %@",self.link);
    [self setupWebView];
    [self setupProgressView];
}
///访问失败通知执行方法
-(void)loadFailFromNotification:(NSNotification *)noti{
    [self example1];
    Reachability *reach = [Reachability reachabilityWithHostName:self.link];
    if ([reach currentReachabilityStatus] != NotReachable){
        [[PAWebView shareInstance] reloadFromOrigin];
    }
}
#pragma mark - Alert loadFail 加载失败弹出框
- (void)example1 {
    zhAlertView *alert = [self alertView1];
    self.zh_popupController = [[zhPopupController alloc] init];
    [self.zh_popupController dropAnimatedWithRotateAngle:30];
    [self.zh_popupController presentContentView:alert duration:0 springAnimated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.zh_popupController dismiss];
    });
}
- (zhAlertView *)alertView1 {
    zhAlertView *alertView = [[zhAlertView alloc] initWithTitle:@"提示"
                                                        message:@"网页加载失败，请稍后重试! "
                                                  constantWidth:290];
    return alertView;
}
- (void)setupProgressView {
    self.progressView = [[LCProgressView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.progressView];
    [self.view bringSubviewToFront:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.webView).offset(0);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(2);
    }];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)setupWebView {
    // 根据生成的WKUserScript对象，初始化WKWebViewConfiguration
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    if (iPhoneX) {
        self.webView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, self.view.bounds.size.width, self.view.bounds.size.height - NAVIGATION_BAR_HEIGHT-15);
    }else{
        self.webView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, self.view.bounds.size.width, self.view.bounds.size.height - NAVIGATION_BAR_HEIGHT);
    }
    self.webView.allowsBackForwardNavigationGestures = YES;//是否允许左右划手势导航,默认不允许
    
    [self.view addSubview:self.webView];
    self.webView.scrollView.bounces = NO;//禁止WebView滚动和回弹方法
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.link]];//创建URL
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:10];//创建NSURLRequest
    [self.webView loadRequest:request];//加载
}
///进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if (self.webView.estimatedProgress < 1.0) {
            self.progressView.delayTime = 1 - self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.progressView.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = 0;
        });
    }
}

- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    //    NSLog(@"JS 调用了 %@ 方法，传回参数 %@",message.name,message.body);
}
/**
 *  在发送请求之前，决定是否跳转
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *url = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
//    NSLog(@"url = %@", url);
    if ([url containsString:@"alipay://"]) {//支付宝
        NSString* dataStr=[url substringFromIndex:23];
        NSLog(@"%@",dataStr);
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[dataStr dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        NSMutableString* mString=[[NSMutableString alloc] init];
        [mString appendString:@"alipays://platformapi/startApp?appId=20000125&orderSuffix="];
        //url进行编码
        [mString appendString:[dict[@"dataString"] codeString]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mString]];
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }else if ([url containsString:@"weixin://"]) {
        NSDictionary *requestHeaders = navigationAction.request.allHTTPHeaderFields;
        if (requestHeaders[@"Referer"]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转
            return;
        }else{
            NSMutableURLRequest *mutableRequest = [navigationAction.request mutableCopy];
            [mutableRequest setValue:@"http://buy.9ku.com/" forHTTPHeaderField:@"Referer"];
            [webView loadRequest:mutableRequest];
        }
        decisionHandler(WKNavigationActionPolicyCancel);//这个地方必须进行不跳转
        return;
    }
    //商城的支付宝支付
    NSArray *array = @[
                       @"http://buy.9ku.com/wap/buy/pay?type=1&no=",
                       @"https://mclient.alipay.com/home/exterfaceAssign.htm",
                       @"https://mapi.alipay.com/gateway.do"
                       ];
    //商城的支付宝支付
    for (NSInteger i = 0; i < array.count; i++) {
        if([url containsString:array[i]]) {
            url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            decisionHandler(WKNavigationActionPolicyCancel);//这个地方必须进行不跳转,否则支付订单会失效
            return;
        }
    }
    // 允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}
//加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    Reachability *reach = [Reachability reachabilityWithHostName:webView.URL.absoluteString];
    if ([reach currentReachabilityStatus] != NotReachable){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.webView reloadFromOrigin];
        });
    }else{
        if ([webView.URL.absoluteString isEqualToString:@"about:blank"]) {
            
        }else{
            [self example1];
        }
    }
}
///为WKWebView 提供webView:shouldPreviewElement: 来预览WebView
- (BOOL)webView:(WKWebView *)webView shouldPreviewElement:(WKPreviewElementInfo *)elementInfo {
    //获取请求的绝对路径.
    NSString *requestURLString = elementInfo.linkURL.absoluteString;
//    NSLog(@"requestURLString = %@", requestURLString);
    return YES;
}
///解决WKWebView新窗口无法打开问题
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}
/// 提示框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示框" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}
@end
